package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"post/api/request"
	"post/glodal"
	"post/model"
	"post/pkg"
)

func Add(context *gin.Context) {
	var req request.PostAdd
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "获取失败",
		})
		return
	}
	pkg.Check(req.Text)
	model := model.Post{
		UserID: req.Userid,
		Title:  req.Title,
		Text:   req.Text,
		Image:  req.Image,
		Type:   req.Type,
		Status: req.Status,
	}
	glodal.DB.Create(&model)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "发布成功",
		"data":    model.ID,
	})
}

func List(context *gin.Context) {
	var req request.PostList
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "获取失败",
		})
		return
	}
	page := req.Page
	if page <= 0 {
		page = 1
	}

	pageSize := req.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var post []model.Post
	glodal.DB.Offset(offset).Limit(req.Size).Where("status=?", req.Status).Order("created_at desc").Find(&post)
	if req.Title != "" {
		glodal.DB.Where("title like ?", "%"+req.Title+"%").Find(&post)
	}
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查看成功",
		"data":    post,
	})
}

func Show(context *gin.Context) {
	var req request.PostShow
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "获取失败",
		})
		return
	}
	var post []model.Post
	glodal.DB.Where("user_id=?", req.Userid).Order("likes desc").Find(&post)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查看成功",
		"data":    post,
	})

}

func PostShow(context *gin.Context) {
	var req request.PostShowList
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "获取失败",
		})
		return
	}
	var post model.Post
	glodal.DB.Where("id=?", req.Id).First(&post)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查看成功",
		"data":    post,
	})
}

func Del(context *gin.Context) {
	var req request.PostDel
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "获取失败",
		})
		return
	}
	var post model.Post
	glodal.DB.Where("id=?", req.Id).Delete(&post)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "删除成功",
	})
}
